package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbBrand;
import com.bwie.service.TbBrandService;
import com.bwie.mapper.TbBrandMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
* @author 牛y
* @description 针对表【tb_brand(品牌表)】的数据库操作Service实现
* @createDate 2025-07-19 10:09:51
*/
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand>
    implements TbBrandService{
    @Autowired
    TbBrandMapper tbBrandMapper;

    @Autowired
    HttpServletRequest request;

    @Override
    public R getBrandList(PageInfoVo pageInfoVo)
    {
        Page<TbBrand> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<TbBrand> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
            wrapper.lambda().like(TbBrand::getBrandName,pageInfoVo.getKeyWord());
        }
        wrapper.lambda().orderByDesc(TbBrand::getCreateTime);
        Page<TbBrand> tbBrandPage = tbBrandMapper.selectPage(page, wrapper);
        return R.OK(tbBrandPage);
    }

    @Override
    public R addBrand(TbBrand tbBrand) {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        String userName = body.get("userName", String.class);
        TbBrand brand = tbBrandMapper.selectOne(new QueryWrapper<TbBrand>().lambda().eq(TbBrand::getBrandName, tbBrand.getBrandName()));
        if(brand!=null){
            return R.ERROR(500,"品牌名称重复");
        }
        tbBrand.setCreateBy(userName);
        tbBrand.setCreateTime(new Date());
        tbBrand.setBrandStatus(0);
        tbBrandMapper.insert(tbBrand);
        return R.OK();
    }

    @Override
    public R updateBrand(TbBrand tbBrand) {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        String userName = body.get("userName", String.class);
        TbBrand brand = tbBrandMapper.selectById(tbBrand.getBrandId());
        if(brand==null){
            return R.ERROR(500,"品牌不存在");
        }
        tbBrand.setUpdateBy(userName);
        tbBrand.setUpdateTime(new Date());
        tbBrandMapper.updateById(tbBrand);
        return R.OK();
    }
}




